package xyz.caijiwang.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import xyz.caijiwang.entity.Img;
import xyz.caijiwang.entity.vo.ImgVo;
import xyz.caijiwang.interceptor.TokenNotValidation;
import xyz.caijiwang.mapper.ImgMapper;
import xyz.caijiwang.response.ResponseEntity;
import xyz.caijiwang.service.ImgService;
import xyz.caijiwang.service.InsertImgService;
import xyz.caijiwang.utils.JwtUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("file")
public class FileController {

    @Autowired
    ImgService imgService;

    @Autowired
    ImgMapper imgMapper;

    @Autowired
    InsertImgService insertImgService;

    //下载图片
    @TokenNotValidation
    @GetMapping("/img/{imgid}")
    public String im(HttpServletResponse response, @PathVariable Integer imgid) {
        ImgVo imgVo = imgMapper.selectByPrimaryKey(imgid);
        return imgService.downloadFile(imgVo.getPath(), response);
    }

    //上传说说图片chat
    @PostMapping("/uploadFilesmore/{articleid}")
    public ResponseEntity uploadFilesmore(HttpServletRequest request, @PathVariable Integer articleid) {
        ResponseEntity responseEntity = new ResponseEntity();
        try {
            String token = request.getHeader("Authorization");
            token = token.substring(7);
            Integer userId = JwtUtil.getUserId(token);
            List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
            List<String> strings = imgService.uploadFilesmore(files, userId);
            if (null != strings && !strings.isEmpty()) {
                String res = "";
                for (String string : strings) {
                    res = res + string + ",";
                }
                res = res.substring(0, res.length() - 1);
                Img img = new Img();
                img.setCreatdate(new Date());
                img.setPath(res);
                insertImgService.insertImgToArticle(img, articleid);
            }
            responseEntity.setInfo("success");
            return responseEntity;
        } catch (Exception e) {
            e.printStackTrace();
            responseEntity.setInfo("error");
            return responseEntity;
        }
    }


}
